package fr.ul.ade.prime.ui;

import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.IBinder;

import com.actionbarsherlock.app.SherlockActivity;

import fr.ul.ade.prime.service.AdeWebService;
import fr.ul.ade.prime.service.AdeWebServiceBinder;

/**
 * Handles the connection to the service for sub-classes of this class.
 * 
 * @author Schnell Michaël
 * @version 1.0
 */
public class AdeWebActivity extends SherlockActivity {

	protected static final String TAG = AdeWebActivity.class.getSimpleName();

	protected AdeWebService service;

	protected ServiceConnection serviceConnection;

	/**
	 * Binds this activity to the AdeWeb service.
	 */
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
	}// onCreate(Bundle)

	@Override
	protected void onStart() {
		super.onStart();

		// Binds the activity to the service and adds a connection listener
		Intent serviceIntent = new Intent(AdeWebService.class.getName());
		this.serviceConnection = new ServiceConnectionAdapter(this);
		this.bindService(serviceIntent, this.serviceConnection,
				Context.BIND_AUTO_CREATE);
	}

	@Override
	protected void onStop() {
		super.onStop();
		this.unbindService(this.serviceConnection);
	}

	protected class ServiceConnectionAdapter implements ServiceConnection {

		protected AdeWebActivity activity;

		protected ServiceConnectionAdapter(AdeWebActivity activity) {
			super();
			this.activity = activity;
		}// ServiceConnectionAdapter(AdeWebActivity)

		@Override
		public void onServiceConnected(ComponentName name, IBinder binder) {
			this.activity.service = ((AdeWebServiceBinder) binder).getService();
		}// onServiceConnected(ComponentName, IBinder)

		@Override
		public void onServiceDisconnected(ComponentName name) {
			this.activity.service = null;
		}// onServiceDisconnected(ComponentName)

	}// class ServiceConnectionAdapter

}// class AdeWebActivity